dojo.provide('app.utils.utils');
(function() {
	dojo.declare('app.utils.keys', null, {
		lastValue : '',
		_onKeyPress : function(e) {
			this.lastValue = this.get('value');
		},
		_onKeyUp : function(e) {
			this._handleEvent(e);
		},
		_onBlur : function(e) {
			this._handleEvent(e);
		},
		_handleEvent : function(e) {
			if (this.time) {
				clearInterval(this.time);
			}
			if (this.get('value') !== this.lastValue) {
				var _self = this;
				this.time = setTimeout(function() {
					_self.onValidInput(e);
				}, 700);
			}
			this.lastValue = this.get('value');
		},
		onValidInput : function(e) {
		}
	});

	dojo.declare('app.map.utils', null, {
		gtimeout : null,
		map : null,
		geocoder : null,
		geocodeUrl : 'http://maps.googleapis.com/maps/api/geocode/json',
		staticMapUrl : 'http://maps.googleapis.com/maps/api/staticmap',
		mapsUrl : 'http://maps.google.com/maps/api/js',
		mapContainerId : 'mapContainer',
		_marker : null,
		_time : 1000,
		constructor : function(args) {
			if (args) {
				this.mapContainerId = args.mapContainerId
						|| this.mapContainerId;
			}
		},
		onGoogle : function() {

		},
		onGoogleError : function(){
			
		},
		initGoogle : function(args) {
			console.log('initGoogle');
			console.log(this);
			var params = {
				sensor : 'false',
				callback : this.declaredClass + '.page.google',
				language: dojo.locale
			}
			dojo.mixin(params, args || {});
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = this.mapsUrl + "?" + dojo.objectToQuery(params);
			console.log(script);
			document.body.appendChild(script);
			this.gtimeout = this._getTimeout(this._time);
			console.log('initGoogle.end');

		},
		_getTimeout : function(time) {
			if (typeof time === 'undefined' || time) {
				var _self = this;
				console.log(time);
				return setTimeout(function() {
					_self.checkGoogle();
				}, time);
			}
		},
		google : function() {
			console.log('google');
			console.log(this);
			var myLatlng = new google.maps.LatLng(-34.397, 150.644);
			var myOptions = {
				zoom : 16,
				center : myLatlng,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			}
			this.map = new google.maps.Map(dojo.byId(this.mapContainerId),
					myOptions);
			this.geocoder = new google.maps.Geocoder();
			this.onGoogle();
			console.log('google.end')

		},
		checkGoogle : function() {
			var nodes = dojo.query('div', this.mapContainerId);
			if (nodes && nodes.length > 0) {
				clearTimeout(this.gtimeout);
				dojo.style(this.mapContainerId, 'visibility', 'visible');
			} else {
				this._time = this._time / 2;
				this._time = this._time < 1 ? 0 : this._time;
				if(this.time){
					this.gtimeout = this._getTimeout(this._time);
				}else{
					this.onGoogleError();
				}
			}
		},
		geocode : function(bag) {
			console.log('geocoding');
			var args = {};
			if (bag.address) {
				args.address = bag.address;
			}
			if (bag.geo) {
				var latLng = new google.maps.LatLng(geo.lat, geo.lng);
				args.latLng = latLng;
			}
			this.geocoder.geocode(args, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK
						|| status == google.maps.GeocoderStatus.ZERO_RESULTS) {
					if (bag.load && typeof bag.load === 'function') {
						bag.load(results);
					}
				} else {
					console.log(status);
					if (bag.error && typeof bag.error === 'function') {
						bag.error(status);
					}
				}
			});
			
		},
		getMarker : function(latLang, args) {
			if (latLang) {
				if (!this._marker) {
					this._marker = new google.maps.Marker(dojo.mixin(
							args || {}, {
								position : latLang,
								map : this.map
							}));
					console.log('new marker');
				} else {
					this._marker.setPosition(latLang);
					console.log('old marker');
				}
			}
			console.log(this._marker);
			return this._marker;
		},
		_dataMapping : {
			'address.street.description' : 'route',
			'address.stNumber' : 'street_number',
			'address.complement' : '',
			'address.zip' : 'postal_code',
			'address.district.description' : 'sublocality',
			'address.city.description' : 'locality',
			'address.state.description' : 'administrative_area_level_1',
			'address.country.description' : 'country',
			'address.lat' : 'lat',
			'address.lng' : 'lng',
			'address.centerLat' : 'centerLat',
			'address.centerLng' : 'centerLng'
		},
		_gResultMapping : {
			'route' : 'address.street.description',
			'street_number' : 'address.stNumber',
			'address.complement' : '',
			'postal_code' : 'address.zip',
			'sublocality' : 'address.district.description',
			'locality' : 'address.city.description',
			'administrative_area_level_1' : 'address.state.description',
			'country' : 'address.country.description'
		},
		_gResultToData : function(gResult, obj) {
			var data = obj || {};
			var cmpts = gResult.address_components;
			var gMap = this._gResultMapping;
			var dMap = this._dataMapping;
			for (idx in cmpts) {
				var cmpt = cmpts[idx];
				var mapping = gMap[cmpt.types[0]];
				if (mapping) {
					data[mapping] = cmpt.long_name;
				}
			}
			var v = gResult.geometry.viewport.getCenter();
			var l = gResult.geometry.location;
			
			data['address.lat'] = l.lat();
			data['address.lng'] = l.lng();
			data['address.centerLat'] = v.lat();
			data['address.centerLng'] = v.lng();
			data['address.json'] = dojo.toJson(gResult);
			return data;
		},
		_setMapPos : function(gResult) {
			console.log(gResult);
			var center = gResult.geometry.viewport.getCenter();
			var loc = gResult.geometry.location;
			this.map.setCenter(center);
			this.getMarker(loc);
		}
	})
	var ucode;
	app.utils.unicodeStr = ucode = function(value) {
		var nv = "";
		if (value && typeof value === "string") {
			for (var i = 0; i < value.length; i++) {
				var val = value.charCodeAt(i);
				if(val < 48 || (val > 57 && val < 65) || (val > 90 && val < 97) || val > 122){
					nv += '%' + new Number(val).toString(16);
				}else{
					nv += value.charAt(i);
				}
			}
		}
		return nv;
	}

	app.utils.objectToQuery = function(obj) {
		var q = [];
		var i = 0;
		for (a in obj) {
			if (obj[a] && obj[a].length > 0) {
				q[i++] = a + "=" + ucode(obj[a]);
			}
		}
		return q.join("&");
	}

})();